package com.app.controller;


import com.app.common.Result;
import com.app.mapper.ConsumptionOrderMapper;
import com.app.model.*;
import com.app.service.*;
import com.app.utils.TokenUtils;
import com.app.vo.ConsumptionOrderVo;
import com.app.vo.OrderVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 16693103420
 * @since 2024-01-31
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private VoucherRecordService voucherRecordService;
    @Autowired
    private UserService userService;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private BusinessService businessService;

    @Autowired
    private IConsumptionOrderService consumptionOrderService;

    @Autowired
    private ConsumptionOrderMapper consumptionOrderMapper;

    // 用户查询订单列表
    @GetMapping("/getUserOrderList")
    public Result getUserOrderList(@RequestParam(defaultValue = "0") Integer page,
                                   @RequestParam(defaultValue = "10") Integer limit, Integer status, String businessName,
                                   Integer classification,
                                   HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        UserModel userModel = userService.getUserByOpenid(openId);
        if (userModel == null) {
            return Result.error(405, "用戶不存在");
        }
        //消费多送订单
        if (classification != null && classification == 5){
            ConsumptionOrderVo vo = consumptionOrderService.queryConsumptionOrderList(page,limit,userModel.getId(),status);
            return Result.success(vo);
        }
        Integer userId = userModel.getId();
        OrderVo userOrderList = orderService.getUserOrderList(page, limit, status, userId, businessName);
        return Result.success(userOrderList);
    }

    /**
     * 商家查询自己售卖的订单数
     * @param page
     * @param limit
     * @param type 1查今天的 2时间不限 3全部
     * @return
     */
    @GetMapping("/businessGetOrders")
    public Result businessGetOrders(@RequestParam(defaultValue = "0") Integer page,@RequestParam(defaultValue = "10") Integer limit, Integer type,HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        UserModel userModel = userService.getUserByOpenid(openId);
        if (userModel == null) {
            return Result.error(405, "用戶不存在");
        }
        String phone = userModel.getPhone();
        BusinessModel businessModel = businessService.getByUserPhone(phone);
        Integer businessId = businessModel.getId();
        return orderService.businessGetOrders(type,businessId,page,limit);
    }

    @GetMapping("/getOrders")
    public Result getOrders() {
        List<BusinessModel> userOrderList = orderService.getOrders();
        return Result.success(userOrderList);
    }

    //根据id查询
    @GetMapping("/getOrderById")
    public Result getOrderById(Integer id) {
        OrderModel order = orderService.getById(id);
        return Result.success(order);
    }

    //用户取消订单
    @Transactional
    @PostMapping("/userCancelOrder")
    public Result userCancelOrder(@RequestBody OrderModel orderModel, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        UserModel userModel = userService.getUserByOpenid(openId);
        if (userModel == null) {
            return Result.error(405, "用戶不存在");
        }
        Integer id = orderModel.getId();
        if (null != orderModel.getClassification() && orderModel.getClassification() == 5){
            QueryWrapper<ConsumptionOrder> qw = new QueryWrapper<>();
            qw.eq("id", orderModel.getId());
            ConsumptionOrder consumptionOrder = consumptionOrderMapper.selectOne(qw);
            consumptionOrder.setStatus(4);
            consumptionOrder.setOrderReason(orderModel.getOrderReason());
            consumptionOrderMapper.updateById(consumptionOrder);
            return Result.success("取消订单成功");
        }
        OrderModel order = orderService.getById(id);
        if (order==null){
            return Result.error(201,"订单不存在");
        }
        if (order.getStatus() != 1) {
            return Result.error(201,"已使用的订单不可取消");
        }
        String message = orderService.userCancelOrder(order, userModel);
        return Result.success(message);
    }

    //根据id删除
    @GetMapping("/delOrder")
    public Result delOrder(Integer id) {
        orderService.removeById(id);
        return Result.success("删除成功");
    }

    /**
     * 获取业务订单列表
     *
     * @param page         第页
     * @param limit        限制
     * @param status       状态
     * @param businessName 企业名称
     * @return {@link Result}
     */
    @GetMapping("/getBusinessOrderList")
    public Result getBusinessOrderList(@RequestParam(defaultValue = "0") Integer page,
                                       @RequestParam(defaultValue = "10") Integer limit, Integer status,
                                       String businessName,
                                       Integer businessId,
                                       String areaId,
                                       String phone,
                                       @RequestParam(required = false) String beginTime,
                                       @RequestParam(required = false) String endTime,
                                       HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String adminId = TokenUtils.verify(token);
        if (adminId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getById(Integer.valueOf(adminId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        OrderVo userOrderList = orderService.getBusinessOrderListUser(page, limit, status, businessName, businessId,beginTime,endTime,user,areaId,phone);
        return Result.success(userOrderList);
    }

    /**
     * 不同状态的订单的数量（待收货、待发货、待使用、待评价）
     * @return
     */
    @GetMapping("/OrderStatusCounts")
    public Result OrderStatusCounts(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        UserModel userModel = userService.getUserByOpenid(openId);
        if (userModel == null) {
            return Result.error(405, "用戶不存在");
        }
        Integer userId = userModel.getId();
        return orderService.OrderStatusCounts(userId);
    }


    /**
     * 订单累计凭证金额
     *
     * @param status       状态
     * @param businessName 企业名称
     * @param businessId   业务id
     * @return {@link Result}
     */
    @GetMapping("/orderCumulativeVoucherAmount")
    public Result orderCumulativeVoucherAmount(Integer status, String businessName,
                                               Integer businessId,HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if ("false".equals(userId)) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        return Result.success(orderService.orderCumulativeVoucherAmount(status, businessName, businessId,user));
    }


    /**
     * 获取滚动列表
     *
     * @return {@link Result}
     */
    @GetMapping("/getRollList")
    public Result getRollList() {
        List<OrderModel> list = orderService.getRollList();
        return Result.success(list);
    }
}

